<template>
	<div>
		<div class="addAgent-content">
			<div class="form-header">
				<h4>{{ $t('funds.capital_adjustment.form_title') }}</h4>
				<span>
					<code style="color: #ff3b30">*</code>
					{{ $t('common.add_dialog_tips') }}
				</span>
			</div>
			<el-divider></el-divider>
			<el-form
				ref="formRef"
				class="form-box"
				:model="queryData"
				:rules="rules"
				label-width="auto"
			>
				<el-form-item
					:label="`${$t('common.choose_merchant')}:`"
					prop="merchantId"
				>
					<merchant-select
						v-model="queryData.merchantId"
						:placeholder="$t('common.please_choose')"
						@change="
							searchUserName
							getConfigMultipleFun
						"
					></merchant-select>
				</el-form-item>
				<el-form-item
					:label="`${$t('funds.user_name')}:`"
					prop="userName"
				>
					<el-input
						v-model.trim="queryData.userName"
						:placeholder="
							$t('funds.capital_adjustment.user_name_placeholder')
						"
						clearable
						minlength="4"
						maxlength="11"
						autocomplete="off"
						@blur="searchUserName"
						style="width: 420px"
					></el-input>
				</el-form-item>
				<!-- <el-form-item
					:label="`${$t('funds.capital_adjustment.real_name')}:`"
					prop="realName"
				>
					<el-input
						v-model.trim="queryData.realName"
						:placeholder="
							$t('funds.capital_adjustment.real_name_placeholder')
						"
						disabled
						autocomplete="off"
					></el-input>
				</el-form-item> -->
				<!-- <el-form-item
					:label="`${$t('funds.capital_adjustment.vip_level')}:`"
					prop="vipLevel"
				>
					<el-input
						v-model="queryData.vipLevel"
						:placeholder="
							$t('funds.capital_adjustment.vip_level_placeholder')
						"
						disabled
						autocomplete="off"
					></el-input>
				</el-form-item> -->
				<el-form-item
					key="accountBalance"
					:label="`${$t('member.balance')}:`"
					prop="accountBalance"
				>
					<el-input-number
						v-model="queryData.accountBalance"
						:placeholder="$t('member.load_center_wallet_banlance')"
						:controls="false"
						disabled
						:precision="2"
						style="width: 310px"
					></el-input-number>
					<span style="position: absolute; left: 4px; color: #909399">
						{{ handleCurrency(currency, true) }}
					</span>
					<el-button
						type="primary"
						:disabled="loading"
						style="margin-left: 15px"
						@click="searchUserName"
					>
						{{ $t('common.search') }}
					</el-button>
				</el-form-item>
				<el-form-item
					key="adjustType"
					:label="`${$t('funds.capital_adjustment.adjust_type')}:`"
					prop="adjustType"
				>
					<el-select
						v-model="queryData.adjustType"
						:placeholder="$t('common.please_choose')"
						@change="getConfigMultipleFun"
					>
						<el-option
							v-for="item in memberPatchAddAdjustTypeArr"
							:key="item.code"
							:label="item.description"
							:value="item.code"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item
					key="amount"
					:label="`${$t('funds.capital_adjustment.less_money')}:`"
					prop="amount"
				>
					<el-input-number
						v-model="queryData.amount"
						:placeholder="
							$t('funds.capital_adjustment.form_rules_tip8')
						"
						:controls="false"
						:min="0.01"
						:max="999999999999.99"
						:precision="2"
						v-input="{ name: 'float', num: '2' }"
						style="width: 420px"
					></el-input-number>
					<span style="position: absolute; left: 4px; color: #909399">
						{{ handleCurrency(currency, true) }}
					</span>
				</el-form-item>
				<el-form-item
					v-if="withdrawLimitType === 2"
					key="validMultiple"
					:label="`${$t('funds.capital_adjustment.bill_multiple')}:`"
					prop="validMultiple"
				>
					<el-input-number
						v-model="queryData.validMultiple"
						:placeholder="
							$t('funds.capital_adjustment.form_rules_tip9')
						"
						:controls="false"
						:min="0"
						:max="10000"
						:precision="2"
						v-input="{ name: 'float', num: '2' }"
						style="width: 420px"
					></el-input-number>
				</el-form-item>
				<el-form-item
					key="remark"
					:label="`${$t('funds.capital_adjustment.remark')}:`"
					prop="remark"
				>
					<el-input
						v-model="queryData.remark"
						type="textarea"
						:placeholder="
							$t('funds.capital_adjustment.remark_placeholder')
						"
						clearable
						show-word-limit
						v-input="{ name: 'noEmpty' }"
						minlength="2"
						maxlength="500"
						style="width: 420px"
					></el-input>
				</el-form-item>
				<el-form-item
					:label="`${$t('funds.capital_adjustment.image_address')}:`"
				>
					<el-col :span="24">
						<UploadMany
							ref="imgUpload"
							:uploadAPI="uploadAPI"
							@setImageAddress="setImageAddress"
						></UploadMany>
					</el-col>
					<el-col :span="24">
						<p class="imgTip">
							{{ $t('funds.capital_adjustment.update_img_tip') }}
						</p>
					</el-col>
				</el-form-item>
				<el-form-item>
					<el-button
						type="primary"
						icon="el-icon-search"
						:disabled="loading"
						@click="handleSubmit"
					>
						{{ $t('common.submit') }}
					</el-button>
					<el-button
						icon="el-icon-refresh-left"
						size="medium"
						@click="reset"
					>
						{{ $t('common.reset') }}
					</el-button>
				</el-form-item>
			</el-form>
		</div>
		<el-dialog
			:close-on-click-modal="false"
			:visible.sync="dialogVisible"
			:destroy-on-close="true"
			:before-close="reset"
			top="40vh"
			width="30%"
		>
			<div style="text-align: center">
				<i
					class="el-icon-success"
					style="font-size: 48px; color: #67c23a"
				></i>
				<h3>
					{{ $t('funds.capital_adjustment.dialog_title') }}
				</h3>
				<p style="display: flex; justify-content: center">
					{{ $t('funds.order_no') }}：
					<Copy :title="eventId" :copy="copy">
						{{ eventId }}
					</Copy>
					&nbsp;
					{{ $t('funds.capital_adjustment.waiting_audit_results') }}
				</p>
				<br />
				<el-button type="primary" size="medium" @click="reset">
					{{ $t('common.back') }}
				</el-button>
			</div>
		</el-dialog>
		<image-viewer
			:visible.sync="imageViewerVisible"
			:url-list="[imageViewerSrc]"
		/>
		<GoogleKeyInput
			:isShowdialog="isShowdialog"
			@getGoogleKey="getGoogleKey($event)"
			@backPrevStep="backPrevStep()"
		></GoogleKeyInput>
	</div>
</template>

<script>
import list from '@/mixins/list'
import { mapGetters } from 'vuex'
import { routerNames } from '@/utils/consts'
import { rules } from './components/rules'
import { LOSE_SYMBOl } from '@/utils/pattern'
export default {
  name: routerNames.membershipIncrease,
  components: {
    UploadMany: () => import('@/components/UploadMany'),
    GoogleKeyInput: () => import('@/components/GoogleKeyInput')
  },
  mixins: [list],
  data() {
    return {
      loading: false,
      queryData: {
        merchantId: '',
        userName: '',
        // realName: '',
        adjustType: '',
        amount: undefined,
        remark: '',
        accountBalance: undefined,
        imageAddress: '',
        googleVerifyCode: undefined,
        validMultiple: 1.00

      },
      // payTypeArr: [],
      showBtb: false,
      isShowdialog: false,
      dialogVisible: false,
      eventId: '',
      imageViewerVisible: false,
      imageViewerSrc: '',
      currency: '',
      withdrawLimitType: 2
    }
  },
  computed: {
    rules() {
      return rules(this)
    },
    ...mapGetters(['merchantInfo', 'googleKeyResult']),
    uploadAPI() {
      return this.$api.imageUpload
    },
    memberPatchAddAdjustTypeArr() {
      return this.globalDics.memberPatchAddAdjustType || []
    }
  },
  watch: {
    'merchantInfo.id': {
      handler(newVal) {
        if (newVal) {
          this.queryData.merchantId = newVal
        }
      },
      immediate: true
    }
  },
  mounted() { },
  methods: {
    setImageAddress(imgList) {
      this.queryData.imageAddress =
        Array.isArray(imgList) && imgList.length > 0
          ? imgList.join(',')
          : undefined
    },
    searchUserName() {
      let flag = false
      this.$refs.formRef.validateField(['merchantId'], (val) => {
        flag = val
      })
      if (!this.queryData.userName) {
        return
      }
      this.$refs.formRef.validateField(['userName'], (val) => {
        if (!flag && !val) {
          this.loading = true
          const params = {
            merchantId: this.queryData.merchantId,
            userName: this.queryData.userName,
            walletType: '1',
            userType: 0
          }
          const _self = this
          this.$api
            .getMemberBalance(params)
            .then((res) => {
              if (res.data) {
                const {
                  balance,
                  userId,
                  // realName,
                  // vipLevel,
                  accountType,
                  currency,
                  withdrawLimitType
                } = res?.data || {}
                _self.currency = currency
                _self.queryData.userId = userId
                // this.queryData.realName = realName
                // this.queryData.vipLevel = vipLevel
                const balanceLimit = _self.handleNumber(currency, balance)
                _self.queryData.accountBalance = balanceLimit?.replace(LOSE_SYMBOl, '')
                _self.queryData.accountType = accountType
                // 2为流水限制,需要展示流水倍数
                _self.withdrawLimitType = withdrawLimitType || 2
              } else {
                _self.$message.error(res.msg)
              }
              setTimeout(() => {
                _self.loading = false
              }, 200)
            })
            .catch(() => {
              _self.loading = false
            })
        }
      })
    },
    getConfigMultipleFun() {
      if (!this.queryData.adjustType || !this.queryData.merchantId || !this.queryData.userName) return
      const str =
        'adjustType=' +
        this.queryData.adjustType +
        '&merchantId=' +
        this.queryData.merchantId + '&username=' + this.queryData.userName
      this.$api
        .getConfigMultiple(str)
        .then((res) => {
          if (res.code === 200) {
            this.queryData.validMultiple = res.data
          }
        })
        .catch(() => {
          this.loading = false
        })
    },
    handleSubmit() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.isShowdialog = true
        }
      })
    },
    backPrevStep() {
      this.loading = false
      this.isShowdialog = false
    },
    getGoogleKey(data) {
      this.queryData.googleVerifyCode = data
      this.isShowdialog = false
      this.loading = true
      const params = {
        ...this.queryData,
        realAccountType: '1'
      }
      // 1为账单限制,默认流水倍数为0
      if (this.withdrawLimitType === 1) {
        params.validMultiple = 0
      }
      this.$api
        .setMemberArtificialPatchAccountAdd(params)
        .then((res) => {
          this.eventId = res?.data
          this.dialogVisible = true
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    reset() {
      this.currency = ''
      this.queryData.imageAddress = ''
      this.$refs?.imgUpload?.resetImgList()
      this.$refs.formRef.resetFields()
      this.queryData.accountBalance = undefined
      this.dialogVisible = false
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep.addAgent-content {
	width: 900px;
	margin: 40px auto;
	border: 1px solid #dcdfe6;
	.form-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 20px 0;
		margin-bottom: -15px;
		color: #909399;
	}
	.form-box {
		width: 800px;
		margin: 20px auto;
		.el-select {
			width: 400px;
		}
		.el-input-number .el-input__inner {
			text-align: left;
		}
		.number-box {
			width: 36px;
			text-align: center;
			position: absolute;
			right: 1px;
			top: 3px;
			color: #909399;
			background: #f5f7fa;
			height: 34px;
			line-height: 34px;
		}
	}
}

.vi_VN,
.th_TH,
.en_US {
	.addAgent-content .form-box {
		width: 700px;
	}

	.addAgent-content .form-box .number-box {
		min-width: 72px;
	}
}
</style>
